package com.its.us.web.config.filter.web;

import com.its.us.web.entity.sys.User;
import com.its.us.web.service.sys.UserDetailsServiceImpl;
import com.its.us.web.utils.*;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义token过滤器
 *
 * @Author: master
 * @Date: 2020/10/29 12:43
 * @Version: 1.0
 */
@Deprecated
public class TokenVerifyFilter extends BasicAuthenticationFilter {


    public TokenVerifyFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    private static JwtTokenUtil jwtTokenUtil;

    private static UserDetailsServiceImpl userService;

    static {
        jwtTokenUtil = SpringContext.getBean(JwtTokenUtil.class);
        userService = SpringContext.getBean(UserDetailsServiceImpl.class);
    }

    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader(ConstantsUtil.Token.TOKEN_NAME);
//        if (header == null || !header.startsWith("Bearer ")) {
        if (token == null) {
            //如果携带错误的token，则给用户提示请登录！
            chain.doFilter(request, response);
            Map<String, Object> map = new HashMap<>();
            map.put("code", 202);
            map.put("msg", "请先登录.");
            ResponseUtil.out(200, response, JsonUtil.toJson(map));
        } else {
            //如果携带了正确格式的token要先得到token
            //String token = header.replace("Bearer ", "");
            User user = new User();
            user.setUsername(jwtTokenUtil.getUsernameFromToken(token));
            //验证tken是否正确
            if (jwtTokenUtil.validateToken(token, user)) {
//                Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                //TODO
                UserDetails userDetails = this.userService.getUserDetails(jwtTokenUtil.getUsernameFromToken(token),false);
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
//                    log.info("authenticated user " + username + ", setting security context");
                //将authentication放入SecurityContextHolder中
                SecurityContextHolder.getContext().setAuthentication(authentication);
                chain.doFilter(request, response);
            }
        }
    }
}
